package edu.sjsu.itack.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.sjsu.itack.bl.UserBl;
import edu.sjsu.itack.entity.User;
import edu.sjsu.itack.util.ITackException;

/**
 * Servlet implementation class SignUpServlet
 */
public class SignUpServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private UserBl service;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SignUpServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void init() throws ServletException {
         service = new UserBl();
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		User user = new User();
		String error="";
		user.setFirstName(request.getParameter("fname"));
        user.setLastName(request.getParameter("lname"));
        user.setGender(request.getParameter("gender"));
		user.setEmail(request.getParameter("email"));
        user.setPassword(request.getParameter("password"));
        if((user.getFirstName()==null|| user.getLastName()==null||user.getGender()==null||user.getEmail()==null||user.getPassword()==null)
        		||(user.getFirstName()==""|| user.getLastName()==""||user.getGender()==""||user.getEmail()==""||user.getPassword()==""))
        {
        	error="Registration failed! Please fill the required fields!";
        	request.setAttribute("error", error);
			request.getRequestDispatcher("signup.jsp").forward(request, response);
        }
        else{
        try {
        	service.signUpUser(user);
        	request.getRequestDispatcher("signin.jsp").forward(request, response);
		} catch (ITackException e) {
			//response.getWriter().write("{status: - 1, msg:"+ e.getLocalizedMessage() +" }");
			request.setAttribute("error", e.getLocalizedMessage());
			request.getRequestDispatcher("signup.jsp").forward(request, response);
		}
        }
      
	}

}
